import { DispatchRtcLib } from './DispatchRtcLib'
/************************** DispatchVideoLib ******************************/
function DispatchVideoLib() {}


var EleResize = {
    _handleResize: function (e) {
        var ele = e.target || e.srcElement;
        var trigger = ele.__resizeTrigger__;
        if (trigger) {
            var handlers = trigger.__z_resizeListeners;
            if (handlers) {
                var size = handlers.length;
                for (var i = 0; i < size; i++) {
                    var h = handlers[i];
                    var handler = h.handler;
                    var context = h.context;
                    handler.apply(context, [context]);
                }
            }
        }
    },
    _removeHandler: function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (handlers) {
            var size = handlers.length;
            for (var i = 0; i < size; i++) {
                var h = handlers[i];
                if (h.handler === handler && h.context === context) {
                    handlers.splice(i, 1);
                    return;
                }
            }
        }
    },
    _createResizeTrigger: function (ele) {
        var obj = document.createElement('object');
        obj.setAttribute('style',
            'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden;opacity: 0; pointer-events: none; z-index: -1;');
        obj.onload = EleResize._handleObjectLoad;
        obj.type = 'text/html';
        ele.appendChild(obj);
        obj.data = 'about:blank';
        return obj;
    },
    _handleObjectLoad: function (evt) {
        this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
        this.contentDocument.defaultView.addEventListener('resize', EleResize._handleResize);
    }
};
if (document.attachEvent) {//ie9-10
    EleResize.on = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (!handlers) {
            handlers = [];
            ele.__z_resizeListeners = handlers;
            ele.__resizeTrigger__ = ele;
            ele.attachEvent('onresize', EleResize._handleResize);
        }
        handlers.push({
            handler: handler,
            context: context
        });
    };
    EleResize.off = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (handlers) {
            EleResize._removeHandler(ele, handler, context);
            if (handlers.length === 0) {
                ele.detachEvent('onresize', EleResize._handleResize);
                delete  ele.__z_resizeListeners;
            }
        }
    }
} else {
    EleResize.on = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (!handlers) {
            handlers = [];
            ele.__z_resizeListeners = handlers;

            if (getComputedStyle(ele, null).position === 'static') {
                ele.style.position = 'relative';
            }
            var obj = EleResize._createResizeTrigger(ele);
            ele.__resizeTrigger__ = obj;
            obj.__resizeElement__ = ele;
        }
        handlers.push({
            handler: handler,
            context: context
        });
    };
    EleResize.off = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (handlers) {
            EleResize._removeHandler(ele, handler, context);
            if (handlers.length === 0) {
                var trigger = ele.__resizeTrigger__;
                if (trigger) {
                    if (trigger.contentDocument) {
                        trigger.contentDocument.defaultView.removeEventListener('resize', EleResize._handleResize);
                    }        
                    ele.removeChild(trigger);
                    delete ele.__resizeTrigger__;
                }
                delete  ele.__z_resizeListeners;
            }
        }
    }
}
  
var DispatchVideoLib_Array = new Array();


var div_resize_listener = function (lib) {
    
    if (lib.div.clientWidth*lib.div.clientHeight == 0)
    {
        return;
    }

    console.log("div_resize " + lib.div.clientWidth + "x" + lib.div.clientHeight);
    
    this.video.style.width=""+lib.div.clientWidth+"px";
    this.video.style.height=""+lib.div.clientHeight+"px";
};


DispatchVideoLib.prototype.Init = function(Div) {
	this.isDispatchVideoLib = true;
	var index = 0;
	for (var i =0; i < 100; i++)
	{
	    if (!DispatchVideoLib_Array[i])
	    {
	        index = i;
	        break;
	    }
	}
	this.index = index;
	DispatchVideoLib_Array[this.index] = this;
	
	Div.DispatchVideoLib = this;

    this.CallID = -1;
    console.log("DispatchVideoLib Init:" + index);
    this.div = Div;
    
    this.video = document.createElement('video');
    this.video.id="DispatchVideo_" + index;
    this.video.style.cssText = "position:absolute;background-color:black; left:0%; top:0%; width:100%; height:100%; z-index:1";
    this.video.autoplay = true;
    this.div.appendChild(this.video);
    
    this.textcanvas = document.createElement('canvas');
    this.textcanvas.style.cssText = "position:absolute; left:80%; top:0%; width:20%; height:30%; z-index:10;";
    this.textcanvas.id="DispatchVideoText_" + index;
    this.div.appendChild(this.textcanvas);
    
    this.text_ctx = this.textcanvas.getContext("2d");
    this.text_ctx.clearRect(0, 0, this.video.width, this.video.height);
    this.text_ctx.font = "30px Arial"
	//this.text_ctx.font = "30px Sans-serif"
    this.text_ctx.fillStyle = "white";
    this.text_ctx.textAlign="right";
    this.text_ctx.textBaseline = 'top';
    
    this.UserText = "";
    
    this.video.videolib = this;

    this.bFull = false;
    this.video.addEventListener('dblclick', function(e) {
        e.currentTarget.videolib.fullscreen();
    }, false);

    EleResize.on(Div, div_resize_listener, this);

    console.log("DispatchVideoLib_" + this.index + " Init");
}

DispatchVideoLib.prototype.Uninit = function() {
    EleResize.off(this.div, div_resize_listener, this);
    this.video.parentNode.removeChild(this.video);
}



DispatchVideoLib.prototype.StartDisplay = function(CallID) {
    this.CallID = CallID;
    this.video.style.objectFit = "contain";
    
    console.log("DispatchVideoLib_" + this.index + " msgInitPlay " + this.CallID);
    
    var videolib = this;
    
    DispatchRtcLib.DisplayVideo(CallID, this);
}

DispatchVideoLib.prototype.StopDisplay = function() {
    if (this.bFull)
    {
        this.fullscreen();
    }
    
    this.video.srcObject = null;
    
    this.CallID = -1;
    this.UserText = "";
    this.clear();
}

DispatchVideoLib.prototype.clear = function(msg) {
    this.text_ctx.clearRect(0, 0, this.text_ctx.canvas.width, this.text_ctx.canvas.height);
}


DispatchVideoLib.prototype.fullscreen = function () {

    
    if (this.bFull){
        if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        } else {
            console.log("Exit fullscreen doesn't work");
        }
        this.bFull = false;
        
        this.restore_pic();
    }
    else{
        if (!this.video.srcObject)
        {
            return;
        }
				
		var div = this.div;
        
        this.save_pic();

        if (div.RequestFullScreen) {
            div.RequestFullScreen();
        } else if (div.webkitRequestFullScreen) {
            div.webkitRequestFullScreen();
        } else if (div.mozRequestFullScreen) {
            div.mozRequestFullScreen();
        } else if (div.msRequestFullscreen) {
            div.msRequestFullscreen();
        } else {
            console.log("This browser doesn't supporter fullscreen");
        }
        this.bFull = true;
    }
};

DispatchVideoLib.prototype.save_pic = function () {
    this.width_before=this.div.clientWidth;
    this.height_before=this.div.clientHeight;
    console.log("DispatchVideoLib_" + this.index + " save_pic " + this.div.clientWidth + "x" + this.div.clientHeight);
};

DispatchVideoLib.prototype.restore_pic = function () {
    this.video.style.width=""+this.width_before+"px";
    this.video.style.height=""+this.height_before+"px";
    console.log("DispatchVideoLib_" + this.index + " restore_pic " + this.width_before + "x" + this.height_before);
};

DispatchVideoLib.prototype.setUserText = function (text) {
    this.UserText = text;
};

DispatchVideoLib.prototype.setVideoText = function (codec, fps, bitrate, width, height) {
    this.codec = codec;
    this.fps = fps;
    this.bitrate = Math.round(bitrate);
    this.width = width;
    this.height = height;
    
    this.text_ctx.clearRect(0, 0, this.text_ctx.canvas.width, this.text_ctx.canvas.height);
    this.text_ctx.fillText(this.codec + " " + this.width + "x" + this.height, this.text_ctx.canvas.width*0.85, this.text_ctx.canvas.height*0.15);
    this.text_ctx.fillText(this.fps + "fps " + this.bitrate + "kps", this.text_ctx.canvas.width*0.85, this.text_ctx.canvas.height*0.15+30);
    this.text_ctx.fillText(this.UserText, this.text_ctx.canvas.width*0.85, this.text_ctx.canvas.height*0.15+60);     
    
};

//设置视频显示模式 0-按比例缩放 1-拉伸
DispatchVideoLib.prototype.setDisplayMode = function (mode) {
    
//"contain"		—— 按比例缩放 全部显示 默认
//"fill"		—— 拉伸
//"cover" 		—— 按比例缩放 会裁剪
//"none"		—— 不缩放
    if (mode == 0)
    {
        this.video.style.objectFit = "contain";
    }
    else
    {
        this.video.style.objectFit = "fill";
    }
};
export { DispatchVideoLib }
